package cn.itsource.user.service.impl;

import cn.itsource.config.RedisService;
import cn.itsource.user.domain.TLogininfo;
import cn.itsource.user.domain.TUser;
import cn.itsource.user.mapper.LogininfoMapper;
import cn.itsource.user.mapper.UserMapper;
import cn.itsource.user.service.IUserService;
import cn.itsource.utils.AjaxResult;
import cn.itsource.utils.HttpClient;
import cn.itsource.utils.MD5;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Transactional
public class UserServiceImpl implements IUserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RedisService redisService;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Override
    public AjaxResult checkPhone(String telephone) {
        TUser user = userMapper.findByPhone(telephone);
        if (user == null) {
            return AjaxResult.me();
        } else {
            return AjaxResult.me().setSuccess(false).setMessage("用户手机号已经被注册");
        }
    }

    @Override
    public AjaxResult sendMobileCode(String phone) {
        //1. 先生成一个6位的随机数字
        String sixNumber = RandomStringUtils.randomNumeric(6);
        //2. 要将当前生成的随机验证码保存到redis，同时将这值设置为有效时长：5分钟
        redisService.setStringKeyAndValue(phone, sixNumber, 5);
        //先不忙着发短信，最后测试短信发送
        System.out.println(">>>>>>>>>验证码=" + sixNumber);
        //2. 调用中国网建的接口，向指定手机号发送一个短信
        String uid = "";//uid是在中国网建上注册后，系统分配的那个帐号
        String key = "";// 短信密钥
        String msgUrl = "http://utf8.api.smschinese.cn/?Uid=" + uid + "&Key=" + key + "&smsMob=" + phone + "&smsText=注册验证码是：" + sixNumber;
        try {
            //在java代码中，如果要发送一个http协议的请求，就会到  httclient工具包
            HttpClient httpClient = new HttpClient(msgUrl);
            httpClient.get();
            //如果获取响应返回的结果
            String content = httpClient.getContent();
            if (Integer.parseInt(content) < 0) {
                return AjaxResult.me().setSuccess(false).setMessage("短信发送失败，请联系管理员！");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return AjaxResult.me();
    }

    @Override
    public AjaxResult register(TUser user) {
//        8. 判断用户传递的验证码与后台redis中保存的验证码是否相同
//        1）如果redis中的验证码已经为空，说明  验证码过期
        String code = redisService.getKeyObjectValue(user.getPhone(), String.class);
        if (StringUtils.isBlank(code)) {
            return AjaxResult.me().setSuccess(false).setMessage("验证码过期");
        }
//        2）如果验证码不同，则说明前端输错
        if (!StringUtils.equals(code, user.getCode())) {
            return AjaxResult.me().setSuccess(false).setMessage("验证码错误");
        }

        //9. 如果验证码校验通过，则注册成功
        //对密码进行加盐处理，同时 md5加密
        //9.1 先通过时间戳来获取一个唯一的随机数，再进行md5加密，来获取盐值
        String salt = MD5.getMD5(System.currentTimeMillis() + "");
        //9.2 再将用户填写的密码与salt进行组合，再进行md5加密
        String secretPass = MD5.getMD5(salt + user.getPassword());
        user.setPassword(secretPass);
        user.setSalt(salt);
        //9.3如果username为空，则默认就是手机号的值
        user.setUsername(StringUtils.isBlank(user.getUsername()) ? user.getPhone() : user.getUsername());
        //添加初始值
        user.setCreatetime(new Date());
        user.setState(TUser.STATE_ZHENGCHANG);
        userMapper.save(user);

        //9.4 注册成功后，将用户的信息，同步一份到t_longininfo表
        TLogininfo logininfo = new TLogininfo();
        logininfo.setUsername(user.getUsername());
        logininfo.setPhone(user.getPhone());
        logininfo.setEmail(user.getEmail());
        logininfo.setSalt(salt);
        logininfo.setPassword(secretPass);
        logininfo.setType(false);
        logininfo.setDisable(true);
        logininfo.setLoginId(user.getId());
        logininfoMapper.insertSelective(logininfo);
        //执行添加操作
        return AjaxResult.me();
    }
}
